import common, { resolveDataCache } from '@/assets/js/common'
import http from '@/common/axios/http'
import axios from 'axios'
import api from '@/common/axios/api'
import weixin from '@/common/axios/weixin'
import { LEVEL_NAME, LEVEL_KEY, LEVEL_ID, LEVEL_ID_UP, LEVEL_INT, LEVEL_NAME_UP } from './area'

const fixCommonId = (list, level) => list.map(i => {
  i.id = i[LEVEL_ID[level]]
  i.name = i[`${LEVEL_NAME[level]}Name`]
  return i
})

const fixCommonUpId = (list, level) => list.map(i => {
  i.id = i[LEVEL_ID_UP[level]]
  i.name = i[LEVEL_NAME_UP[level]]
  return i
})

const fetchByLevelKey = async (api, level, key) => {
  let res = await http.get(api, {
    [LEVEL_KEY[level]]: key
  })
  return res.data ? res.data.data : null
}

const actions = {
  async fetchUsers (ctx) {
    ctx.commit('fetchUsers', (await axios.get('/static/data/test.json')).data.users)
  },
  async refreshUser (ctx) {
    if (ctx.state.user) {
      await ctx.dispatch('fetchUsers')
      ctx.commit('setUser', ctx.state.users.filter(u => u.id === ctx.state.user.id)[0])
      ctx.commit('persistUser')
      // 不保存当前面包屑
    }
  },
  // 缓存市区Id列表
  async fetchAreaIdList (ctx) {
    const key = `area${ctx.state.user.provinceId.toString()}`
    const handle = async () => {
      const res = await weixin.getCityList(ctx.state.user.provinceId)
      ctx.commit('changeAreaIdList', res)
    }
    await resolveDataCache(key, handle)
  },
  async fetchGardenIdList (ctx) {
    const key = `garden${ctx.getters.userLevel}${ctx.state.user.area}`
    const handle = async () => {
      ctx.commit('changeGardenIdList', (await fetchByLevelKey(api.resolvegarden, ctx.getters.userLevel, ctx.state.user.area)))
    }
    await resolveDataCache(key, handle)
  },
  // 初始化市级列表
  async fetchCityMap (ctx) {
    if (!ctx.getters.cityMapFetched) {
      ctx.commit('fetchCityMap', (await axios.get('/static/map/cityMap.json')).data)
    }
  },
  async fetchProvinces (ctx) {
    if (!ctx.getters.provincesFetched) {
      ctx.commit('fetchProvinces', (await axios.get('/static/map/provinces.json')).data)
    }
  },
  async fetchMapFeatures (ctx) {
    if (ctx.state.mapArea && ctx.state.cityMap && ctx.state.provinces) {
      let res
      switch (ctx.getters.areaLevel) {
        case '省级':
          res = (await axios.get('/static/map/province/' + ctx.state.provinces[common.shortProvince(ctx.getters.area)] + '.json')).data
          break
        case '市级':
          res = (await axios.get('/static/map/city/' + ctx.state.cityMap[ctx.getters.area] + '.json')).data
          break
        case '区级':
          res = (await axios.get('/static/map/city/' + ctx.state.cityMap[ctx.state.crumbs[1].name] + '.json')).data
          // 筛选出当前县数据
          res.features = res.features.filter(f => f.properties.name === ctx.getters.area)
          await ctx.dispatch('fetchGardenIdList')
          break
        default:
          return
      }
      ctx.commit('fetchMapFeatures', res)
    }
  },
  async fetchGeneralOverview (ctx) {
    ctx.commit('fetchGeneralOverview', (await fetchByLevelKey(api.generalOverview, ctx.getters.areaLevel, ctx.getters.areaKey)))
  },
  async fetchSleepOverview (ctx) {
    ctx.commit('fetchSleepOverview', (await fetchByLevelKey(api.sleepOverview, ctx.getters.areaLevel, ctx.getters.areaKey)))
  },
  async fetchSportAndSleep (ctx) {
    ctx.commit('fetchSportAndSleep', (await fetchByLevelKey(api.sportAndSleep, ctx.getters.areaLevel, ctx.getters.areaKey)))
  },
  async fetchAttendOverview (ctx) {
    ctx.commit('fetchAttendOverview', (await fetchByLevelKey(api.attendOverview, ctx.getters.areaLevel, ctx.getters.areaKey)))
  },
  async fetchAttend (ctx) {
    let res = await fetchByLevelKey(api[LEVEL_NAME[ctx.getters.areaLevel]], ctx.getters.areaLevel, ctx.getters.areaKey)
    ctx.commit('fetchAttend', fixCommonId(res, ctx.getters.subAreaLevel))
  },
  async fetchGradeSportAndSleep (ctx) {
    ctx.commit('fetchGradeSportAndSleep', (await fetchByLevelKey(api.getAverageSleepRange, ctx.getters.areaLevel, ctx.getters.areaKey)))
  },
  async fetchCheck (ctx) {
    const { areaLevel: level } = ctx.getters
    const { mapArea } = ctx.state
    let opt = {
      ProvinceId: ctx.state.user.provinceId,
      CityId: 0,
      DistrictId: 0,
      Gid: 0
    }
    if (LEVEL_INT[level] > LEVEL_INT['区级']) {
      const { gardenIdList } = ctx.state
      const garden = gardenIdList.filter(g => g.gardenId === mapArea.id)[0]
      const { cityId, districtId, gardenId } = garden
      opt = {
        ...opt,
        CityId: cityId,
        DistrictId: districtId,
        Gid: gardenId
      }
    } else if (LEVEL_INT[level] > LEVEL_INT['省级']) {
      const { areaIdList } = ctx.state
      const area = areaIdList.filter(a => a[LEVEL_ID_UP[level]] === mapArea.id)[0]
      opt.CityId = area.CityId
      if (LEVEL_INT[level] > LEVEL_INT['市级']) {
        opt.DistrictId = area.DistrictId
      }
    }

    if (LEVEL_INT[level] > LEVEL_INT['区级']) {
      ctx.commit('fetchAvgGardenCheck', await weixin.getGardenAvgDataList(mapArea.id))
    } else {
      ctx.commit('fetchAvgCheck', await weixin.getAvgBodyCheckResult(opt))
    }

    let res = await weixin.getBodyCheckResultList(opt)
    if (LEVEL_INT[level] > LEVEL_INT['省级']) {
      res = res.filter(c => c[LEVEL_ID_UP[level]] === mapArea.id)
    }
    ctx.commit('fetchCheck', fixCommonUpId(res, ctx.getters.subAreaLevel))
  },
  changeAreaIdList (ctx, areaIdList) {
    ctx.commit('changeAreaIdList', areaIdList)
  },
  changeGardenIdList (ctx, gardenIdList) {
    ctx.commit('changeGardenIdList', gardenIdList)
  }
}

export default actions
